use crate::app::server::conn;
use crate::app::server::message;
use crate::app::server::message::Message;
use std::collections::HashMap;
use std::sync::Arc;

pub trait Handle {
    fn handle(&self, _client: &mut conn::ConnEntity, _msg: message::Message) -> (bool, Message) {
        (
            true,
            Message::new(
                0,
                "未定义消息处理函数，请检查消息头是否正确"
                    .as_bytes()
                    .to_vec(),
            ),
        )
    }
}
pub trait Handlers {
    fn register(&mut self, status: u16, call: Arc<dyn Handle + Send + 'static>);
    fn get_call_func(&mut self, status: u16) -> Option<Arc<dyn Handle + Send>>;
}

#[derive(Clone)]
pub struct HandlerManage {
    pub handle_func: HashMap<u16, Arc<dyn Handle + Send + 'static>>,
}

impl HandlerManage {
    pub fn new() -> Self {
        HandlerManage {
            handle_func: HashMap::new(),
        }
    }
    pub fn register(&mut self, status: u16, call: Arc<dyn Handle + Send + 'static>) {
        self.handle_func.insert(status, call);
    }
    pub fn get_mut_call_func(&mut self, status: u16) -> Option<Arc<dyn Handle + Send>> {
        self.handle_func.get_mut(&status).cloned()
    }
    pub fn get_call_func(&self, status: u16) -> Option<Arc<dyn Handle + Send>> {
        self.handle_func.get(&status).cloned()
    }
}

pub trait ConnHook {
    fn conn_success(&self, client: &mut conn::ConnEntity);
    fn conn_close(&self, client: &mut conn::ConnEntity);
}
pub struct ConnHookDefault {}
impl ConnHook for ConnHookDefault {
    fn conn_success(&self, client: &mut conn::ConnEntity) {
        log_info_ln!(
            "new client connect success it`s {}:{}",
            client.addr.ip(),
            client.addr.port()
        );
    }
    fn conn_close(&self, client: &mut conn::ConnEntity) {
        log_info_ln!(
            "The client is disconnected it`s {}:{}",
            client.addr.ip(),
            client.addr.port()
        );
    }
}
